package com.agrimall.servlet.client;

import com.agrimall.entity.User;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

/**
 * 客户端用户管理Servlet
 */
@WebServlet("/client/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("profile")) {
            // 个人中心
            userProfile(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("profile")) {
            // 更新个人信息
            updateProfile(request, response, user);
        } else if (action != null && action.equals("changePassword")) {
            // 修改密码
            changePassword(request, response, user);
        } else if (action != null && action.equals("recharge")) {
            // 充值
            recharge(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 个人中心
     */
    private void userProfile(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        User latestUser = userService.getUserById(user.getUserId());
        if (latestUser != null) {
            request.getSession().setAttribute("user", latestUser);
            request.setAttribute("user", latestUser);
        } else {
            request.setAttribute("user", user);
        }
        
        request.getRequestDispatcher("/client/user/profile.jsp").forward(request, response);
    }
    
    /**
     * 更新个人信息
     */
    private void updateProfile(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");
        
        User updateUser = new User();
        updateUser.setUserId(user.getUserId());
        updateUser.setRealName(realName);
        updateUser.setPhone(phone);
        updateUser.setEmail(email);
        updateUser.setAddress(address);
        
        boolean success = userService.updateUser(updateUser);
        
        if (success) {
            User updatedUser = userService.getUserById(user.getUserId());
            if (updatedUser != null) {
                request.getSession().setAttribute("user", updatedUser);
                request.setAttribute("user", updatedUser);
                request.setAttribute("message", "个人信息修改成功！");
            } else {
                request.setAttribute("user", user);
                request.setAttribute("error", "更新成功，但获取最新信息失败");
            }
        } else {
            request.setAttribute("user", user);
            request.setAttribute("error", "个人信息修改失败，请重试");
        }
        
        request.getRequestDispatcher("/client/user/profile.jsp").forward(request, response);
    }
    
    /**
     * 修改密码
     */
    private void changePassword(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String oldPassword = request.getParameter("oldPassword");
            String newPassword = request.getParameter("newPassword");
            String confirmPassword = request.getParameter("confirmPassword");
            
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请输入当前密码\"}");
                out.flush();
                return;
            }
            
            if (newPassword == null || newPassword.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请输入新密码\"}");
                out.flush();
                return;
            }
            
            if (confirmPassword == null || confirmPassword.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请确认新密码\"}");
                out.flush();
                return;
            }
            
            if (!newPassword.equals(confirmPassword)) {
                out.print("{\"success\":false,\"message\":\"新密码和确认密码不一致\"}");
                out.flush();
                return;
            }
            
            if (newPassword.length() < 6) {
                out.print("{\"success\":false,\"message\":\"新密码长度至少6位\"}");
                out.flush();
                return;
            }
            
            boolean success = userService.changePassword(user.getUserId(), oldPassword, newPassword);
            
            if (success) {
                out.print("{\"success\":true,\"message\":\"密码修改成功！\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"密码修改失败，当前密码错误或操作失败\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"密码修改失败：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 充值
     */
    private void recharge(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String amountStr = request.getParameter("amount");
            if (amountStr == null || amountStr.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请输入充值金额\"}");
                out.flush();
                return;
            }
            
            amountStr = amountStr.trim();
            
            if (!amountStr.matches("^\\d+(\\.\\d{1,2})?$")) {
                out.print("{\"success\":false,\"message\":\"请输入有效的金额格式（最多2位小数）\"}");
                out.flush();
                return;
            }
            
            BigDecimal amount;
            try {
                amount = new BigDecimal(amountStr);
            } catch (NumberFormatException e) {
                out.print("{\"success\":false,\"message\":\"请输入有效的金额\"}");
                out.flush();
                return;
            }
            
            if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                out.print("{\"success\":false,\"message\":\"充值金额必须大于0\"}");
                out.flush();
                return;
            }
            
            BigDecimal minAmount = new BigDecimal("0.01");
            if (amount.compareTo(minAmount) < 0) {
                out.print("{\"success\":false,\"message\":\"充值金额不能少于0.01元\"}");
                out.flush();
                return;
            }
            
            BigDecimal maxAmount = new BigDecimal("999999.99");
            if (amount.compareTo(maxAmount) > 0) {
                out.print("{\"success\":false,\"message\":\"单次充值金额不能超过999,999.99元\"}");
                out.flush();
                return;
            }
            
            int scale = amount.scale();
            if (scale > 2) {
                out.print("{\"success\":false,\"message\":\"金额最多保留2位小数\"}");
                out.flush();
                return;
            }
            
            boolean success = userService.rechargeBalance(user.getUserId(), amount);
            
            if (success) {
                User updatedUser = userService.getUserById(user.getUserId());
                if (updatedUser != null) {
                    request.getSession().setAttribute("user", updatedUser);
                    out.print("{\"success\":true,\"message\":\"充值成功！当前余额：¥" + updatedUser.getBalance() + "\",\"balance\":\"" + updatedUser.getBalance() + "\"}");
                } else {
                    out.print("{\"success\":true,\"message\":\"充值成功，但获取最新余额失败\"}");
                }
            } else {
                out.print("{\"success\":false,\"message\":\"充值失败，请重试\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"充值失败：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}

